package com.ruoyi.web.admin.data.command;

import com.ruoyi.system.domain.SysDevice;
import com.ruoyi.system.service.ISysDeviceCollectRecordService;
import com.ruoyi.system.service.ISysDeviceService;
import com.ruoyi.web.admin.data.Constants;
import com.ruoyi.web.admin.data.utils.CommonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 电量数据上报命令处理器
 *
 * @author 10100
 */
@Component
public class AlarmPowerCommandHandler implements CommandHandler {

    private static final Logger log = LoggerFactory.getLogger(AlarmPowerCommandHandler.class);

    @Resource
    private ISysDeviceService sysDeviceService;

    @Resource
    private ISysDeviceCollectRecordService sysDeviceCollectRecordService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String handle(String deviceId, String iccid, String recordId, String command,
                         String type, String timestamp, String length, String body) {
        log.info("设备[{}]电量数据上报：{}", deviceId, body);

        //更新设备数据
        try {
            // 解析心率数据并存储到数据库
            String[] healthData = body.split("@");
            String powerStatus = healthData[0];
            String power = healthData[1].replace("%", "");

            SysDevice device = sysDeviceService.selectSysDeviceByeIdentifier(deviceId);
            if (device != null) {
                device.setPowerStatus(powerStatus);
                device.setBatteryLevel(Integer.parseInt(power));
                device.setConnectionStatus("1");
                device.setLastHeartbeatTime(new Date());
                sysDeviceService.updateSysDevice(device);

                sysDeviceCollectRecordService.insertRecord(device, "POWER", power, "");
            } else {
                // 设备不存在，创建新设备记录
                log.info("设备[{}]不存在，健康数据忽略", deviceId);
                return null;
            }
        } catch (Exception e) {
            log.error("更新设备[{}]状态时发生错误: {}", deviceId, e.getMessage(), e);
        }

        // 构建响应格式
        String responseBody = "0";
        return "[" + deviceId + "," +
                iccid + "," +
                CommonUtils.generateSerialNumber() + "," +
                command + "," +
                Constants.REPORT_RESPONSE + "," +
                CommonUtils.getCurrentTimestamp() + "," +
                responseBody.length() + "," +
                responseBody + "]";
    }

    @Override
    public String getCommandType() {
        return "ALARM_POWER";
    }
}